package cn.shuto.liferay.plugin.chart.service.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;

import cn.shuto.liferay.plugin.chart.service.model.DataSourceCfg;
import cn.shuto.liferay.plugin.chart.service.service.DataSourceCfgLocalServiceUtil;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceFactory {

	private static HashMap<String, ComboPooledDataSource> dss = new HashMap<String, ComboPooledDataSource>();

	private synchronized static ComboPooledDataSource getDataSource(
			final String dsName) {
		ComboPooledDataSource ds = null;
		if ((ds = dss.get(dsName)) == null) {
			ds = new ComboPooledDataSource();
			try {
				DataSourceCfg dscfg = DataSourceCfgLocalServiceUtil.getDataSourceCfg(Long.valueOf(dsName));
				ds.setDriverClass(dscfg.getDriver());
				ds.setUser(dscfg.getDbusername());
				ds.setPassword(dscfg.getDbpassword());
				ds.setJdbcUrl(dscfg.getConnUrl());
				ds.setInitialPoolSize(5);
				ds.setMinPoolSize(1);
				ds.setMaxPoolSize(15);
				ds.setMaxStatements(50);
				ds.setMaxIdleTime(6000);
				dss.put(dsName, ds);
			} catch (Exception e) {
				_log.error(e, e);
				throw new RuntimeException("创建连接池失败：" + dsName);
			}
			dss.put(dsName, ds);
		}
		return ds;
	}

	public static Connection getConnection(String dsName) {
		return getConnection(dsName, false);
	}
	public static Connection getConnection(String dsName,boolean reconnect ) {
		if(reconnect){
			if(dss.containsKey(dsName)){
				dss.get(dsName).close();
				dss.remove(dsName);
			}
		}
		ComboPooledDataSource ds = getDataSource(dsName);
		Connection conn = null;
		try {
			conn = ds.getConnection();
		} catch (Exception e) {
			_log.error(e, e);
			throw new RuntimeException("获取连接失败：" + dsName);
		}
		return conn;
	}

	public static void close(Connection conn) {
		if (conn != null) {
			try {
				if (!conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				_log.error(e);
			}
			conn = null;
		}
	}
	
	private static Log _log = LogFactoryUtil.getLog(DataSourceFactory.class);
}
